/*
 * Created on Sep 18, 2004
 */
package org.vectrics.user;

import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;
import org.vectrics.common.util.DateSync;
import org.vectrics.domain.Domain;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.hibernate.HibernateUtil;
import org.vectrics.history.HistoryProvider;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.Request;

/**
 * ServiceRequestWriter will save an HTTP Request to the database as a ServiceRequest object.
 * @author mmoore
 */
public class ServiceRequestWriter {
	
	
	public ServiceRequest save(Request request) {
	
		Domain domain = CoreServiceLocator.getUserAuthService().getSessionDomain(request);
		ServiceRequest serviceRequest = new ServiceRequest();
		serviceRequest.setClientIp(request.getRemoteAddr());
		serviceRequest.setSessionId(request.getSessionId());
		Person person = null;
		if (domain != null) {
			person = CoreServiceLocator.getUserAuthService().getAuthorizedPerson(domain, request);
		}
		
		if (person != null)
		    serviceRequest.setPersonId(person.getId());
		serviceRequest.setTimeStamp(DateSync.getCurrentTime());
		serviceRequest.setRequest(request.getRequestURI());
		serviceRequest.setCountry(request.getLocale().getISO3Country());
		serviceRequest.setLanguage(request.getLocale().getISO3Language());
		StringBuffer params = new StringBuffer();
		Iterator paramIter = request.getParameterNames().iterator();
		while (paramIter.hasNext()) {
		    String paramName = (String)paramIter.next();
		    String paramValue = request.getParameter(paramName);
		    params.append(paramName + "=" + paramValue + " | ");
		}
		
		ThreadProperties.forcedCommit();
		Person savePerson = ThreadProperties.getPerson();
		ThreadProperties.setSystemUser(true);
		ThreadProperties.setPerson(CoreServiceLocator.getConfiguration().getSystemPerson());
		HistoryProvider.getInstance().saveServiceRequest(serviceRequest);
		ThreadProperties.forcedCommit();
		ThreadProperties.setSystemUser(false);
		ThreadProperties.setPerson(savePerson);
		
		return(serviceRequest);
	}
	
	public void saveError(String error, ServiceRequest serviceRequest) {
		// Start a new session just in case old was rolledback from exception
		HibernateUtil hibernate =
				(HibernateUtil)CoreServiceLocator.findServiceBean("hibernate.util");
		Session session = hibernate.getSessionFactory().openSession();
		serviceRequest.setError(error);
		session.update(serviceRequest);
		session.flush();
		session.close();
	}

}
